<?php

/**
 * +----------------------------------------------------------------------+
 * php23种设计模式实现-迭代器模式
 * Author：微信公众号：yuantanphp
 * 获取更多资源，技术答疑，项目合作请关注微信公众号：yuantanphp
 * +----------------------------------------------------------------------+
 */
 namespace Iterator;
//抽象迭代器
abstract class Iterator
{
    public abstract function First();
    public abstract function Next();
    public abstract function IsDone();
    public abstract function CurrentItem();
}
 
//具体迭代器
class ConcreteIterator extends Iterator
{
    private $aggre;
    private $current = 0;
    public function __construct(array $_aggre)
    {
        $this->aggre = $_aggre;
    }
    //返回第一个
    public function First()
    {
        return $this->aggre[0];
    }
 
    //返回下一个
    public function  Next()
    {
        $this->current++;
        if($this->current<count($this->aggre))
        {
            return $this->aggre[$this->current];
        }
        return false;
    }
 
    //返回是否IsDone
    public function IsDone()
    {
        return $this->current>=count($this->aggre)?true:false;
    }
 
    //返回当前聚集对象
    public function CurrentItem()
    {
        return $this->aggre[$this->current];
    }
}

$motor = [];
for($i = 0; $i <= 99; $i++)
{
    $key = $i+1;
    $motor[$i] = "Motor_".$key;
}
$iterator= new ConcreteIterator($motor);
while(!$iterator->IsDone())
{
    echo "{$iterator->CurrentItem()}：已经检测！<br/>";
    $iterator->Next();
}
